package com.example.experiment07.controller;

import com.example.experiment07.component.JWTComponent;
import com.example.experiment07.entity.User;
import com.example.experiment07.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: YancyZhang
 * @time: 2022/6/21 14:51
 */
@Slf4j
@RestController
@RequestMapping("/api/")
public class LoginController {
    @Autowired
    JWTComponent jwtComponent;
    List<User> userList = new ArrayList<>();
    @Autowired
    private PasswordEncoder passwordEncoder;
    @PostMapping("register")
    public ResultVO register(@RequestBody User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userList.add(user);
        System.out.println(userList);
        return ResultVO.success(Map.of("msg","注册成功！"));
    }
    @PostMapping("login")
    public ResultVO login(@RequestBody User user, HttpServletResponse response) {
        // 先查询用户是否存在
        User u = null;
        for(int i = 0; i < userList.size(); i++){
            if(userList.get(i).getName().equals(user.getName())){
                u = userList.get(i);
            }
        }
        System.out.println(u);
        if (u == null || !passwordEncoder.matches(user.getPassword(), u.getPassword())) {
            log.debug("登录失败");
            return ResultVO.error(401, "用户名密码错误");
        }
        // 登录成功，添加token等操作
        log.debug("登录成功");
        response.addHeader("token", jwtComponent.encode(Map.of("userId", u.getId())));
        return ResultVO.success(Map.of("user", u));
    }
}